<?php
/**
 * 后台首页
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Index extends Base{
    protected function _initialize(){
        $this->needAuth = false;  // 关闭权限验证
        parent::_initialize();
        $this->config = get_config();
    }

    /**
     * 首页框架
     * @return \think\response\View
     */
    public function index(){
        // 获取当前用户及分组信息
        $info = $this->admin
            ->alias('a')
            ->field('a.id,a.username,a.portrait,c.group_name,c.auth_ids')
            ->join([['auth_group_access b','a.id = b.uid','inner'],['auth_group c','b.group_id = c.id','inner']])
            ->where(['a.id'=>$this->id])
            ->find();
        // 权限菜单
        $auth = self::_menu($info);
        // 获取配置文件信息
        return view('index',['config'=>$this->config,'auth'=>$auth,'info'=>$info]);
    }

    /**
     * 首页内容
     * @return \think\response\View
     */
    public function main(){
        // 获取登录信息
        $info = $this->admin
            ->field('login_times,last_login_ip,last_login_time')
            ->where(['id'=>$this->id])
            ->find();
        return view('main',['config'=>$this->config,'info'=>$info]);
    }

    /**
     * 菜单
     * @param $info
     * @return array
     */
    protected function _menu($info){
        // 超级管理员至高无上
        $where = $this->id == \Param::GROUP_ADMIN ? ['status'=>\Param::STATUS_ON] : ['id'=>['in',$info['auth_ids']],'status'=>\Param::STATUS_ON];
        // 获取当前用户具备的权限
        $auth_rules  = $this->getList($this->auth_rule, $where,'','sort desc');

        $auth = array();
        $sub  = array();
        foreach($auth_rules as $k=>$v){
            if ($v['pid'] == 0) {
                $auth[] = $v;
            } else {
                $sub[] = $v;
            }
        }
        // 组合权限菜单
        foreach($auth as $k=>$v){
            foreach($sub as $k1=>$v1){
                if($v['id'] == $v1['pid']){
                    $auth[$k]['sub'][]  = $v1;
                }
            }
        }
        return $auth;
    }
}